import React, { useState, useEffect, useCallback, useMemo } from 'react'
import {
    View,
    ScrollView,
    TouchableOpacity,
    Alert,
    BackHandler,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useForm, useFieldArray } from 'react-hook-form'
import {
    Text,
} from '@rneui/themed'
import { useRoute, useNavigation, CommonActions, useFocusEffect } from '@react-navigation/native'
import type { RouteProp } from '@react-navigation/native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { LeaveFormData } from '../../api/leave'
import { useLeaveDict } from '../../hooks/useDict'
import { DICT_TYPE } from '../../api/dict'
import { leaveStyles } from '../../styles/leaveStyles'
import { formatDate } from '../../utils/dateFormatter'
import { ResearchForm } from './components/ResearchForm'
import { TrainingForm } from './components/TrainingForm'
import { PersonalForm } from './components/PersonalForm'
import { BusinessForm } from './components/BusinessForm'
import { AcademicForm } from './components/AcademicForm'
import { OtherForm } from './components/OtherForm'
import { useLeaveSubmission } from './hooks/useLeaveSubmission'

type LeaveReasonDetailRouteProp = RouteProp<{
    LeaveReasonDetail: {
        selectedReasons: (string | number)[]
        startDate: string
        endDate: string
        onSave: (reasonData: any) => void
        // 主请假申请数据
        mainLeaveData?: {
            destinations?: string[]
            workArrangement?: string
            remark?: string
            hostId?: string
            personId?: string
            personAdmitId?: string
            deptId?: string
            registerId?: number // 编辑模式下的请假登记ID
        }
        // 编辑模式下的请假事由详情数据
        editReasonData?: any[]
    }
}, 'LeaveReasonDetail'>

export const LeaveReasonDetail: React.FC = () => {
    const route = useRoute<LeaveReasonDetailRouteProp>()
    const navigation = useNavigation()
    const { selectedReasons, startDate, endDate, onSave, mainLeaveData, editReasonData } = route.params
    const [currentReasonIndex, setCurrentReasonIndex] = useState(0)
    const [isDataLoaded, setIsDataLoaded] = useState(false)
    
    // 草稿相关状态
    const [hasDraft, setHasDraft] = useState(false)
    const [isFormDirty, setIsFormDirty] = useState(false)
    const [isSubmitted, setIsSubmitted] = useState(false) // 添加提交状态标记
    const [isShowingAlert, setIsShowingAlert] = useState(false) // 防止重复弹窗

    // 使用字典Hook获取请假相关字典数据
    const { 
        getIntDictOptions,
    } = useLeaveDict()

    // 根据选中的事由生成初始默认值
    const defaultValues = useMemo(() => {
        const values: any = {
            researchItems: [],
            trainingItems: [],
            businessItems: [],
            personalItems: [],
            academicItems: [],
            otherItems: [],
        }

        // 如果有编辑数据，使用编辑数据
        if (editReasonData && editReasonData.length > 0) {
            // 按类型分组编辑数据
            const groupedEditData = editReasonData.reduce((groups: any, item: any) => {
                const type = item.type || 0
                if (!groups[type]) {
                    groups[type] = []
                }
                groups[type].push(item)
                return groups
            }, {})
            
            // 填充各种类型的请假事由
            if (groupedEditData[1]) { // 调研
                values.researchItems = groupedEditData[1].map((item: any) => ({
                    id: item.id, // 添加ID字段，用于区分更新还是创建
                    startDate: formatDate(item.startDate) || startDate || "",
                    endDate: formatDate(item.endDate) || endDate || "",
                    theme: item.subject || "",
                    purpose: item.purpose || "",
                    organization: item.unit || ""
                }))
            }
            
            if (groupedEditData[2]) { // 培训
                values.trainingItems = groupedEditData[2].map((item: any) => ({
                    id: item.id, 
                    startDate: formatDate(item.startDate) || startDate || "",
                    endDate: formatDate(item.endDate) || endDate || "",
                    theme: item.subject || "",
                    organization: item.unit || ""
                }))
            }
            
            if (groupedEditData[3]) { // 公务
                values.businessItems = groupedEditData[3].map((item: any) => ({
                    id: item.id, 
                    startDate: formatDate(item.startDate) || startDate || "",
                    endDate: formatDate(item.endDate) || endDate || "",
                    meetingName: item.subject || "",
                    organization: item.unit || ""
                }))
            }
            
            if (groupedEditData[4]) { // 因私
                values.personalItems = groupedEditData[4].map((item: any) => ({
                    id: item.id, 
                    startDate: formatDate(item.startDate) || startDate || "",
                    endDate: formatDate(item.endDate) || endDate || "",
                    type: String(item.privateType || ""),
                    details: item.detail || "",
                    phone: item.phone || "",
                    route: item.visitRoute || "",
                    relation: item.relationship || "",
                    visitName: item.visitedPersonName || "",
                    visitType: String(item.visitType || ""),
                    visitAddress: item.registeredAddress || "",
                    maritalStatus: String(item.maritalStatus || ""),
                    parity: String(item.birthCount || ""),
                    multiple: String(item.multipleBirth || ""),
                    dystocia: String(item.difficultBirth || "")
                }))
            }
            
            if (groupedEditData[5]) { // 学术会议
                values.academicItems = groupedEditData[5].map((item: any) => ({
                    id: item.id,
                    startDate: formatDate(item.startDate) || startDate || "",
                    endDate: formatDate(item.endDate) || endDate || "",
                    meetingName: item.subject || "",
                    organizer: item.unit || "",
                    nature: item.meetingNature || "",
                    hasReport: item.reportType ? 1 : 0, // 根据是否有reportType判断是否受邀作报告
                    reportType: Number(item.reportType || 0),
                    reportTitle: item.reportTitle || "",
                    academicPaperCount: Number(item.reportPaperCount || 0)
                }))
            }
            
            if (groupedEditData[6]) { // 其他
                values.otherItems = groupedEditData[6].map((item: any) => ({
                    id: item.id, 
                    description: item.detail || ""
                }))
            }
        } else {
            // 新增模式，使用默认值
            selectedReasons.forEach(reason => {
                const reasonNum = Number(reason)
                switch (reasonNum) {
                    case 1: // Research
                        values.researchItems = [{ startDate: startDate || "", endDate: endDate || "", theme: "", purpose: "", organization: "" }]
                        break
                    case 2: // Training
                        values.trainingItems = [{ startDate: startDate || "", endDate: endDate || "", theme: "", organization: "" }]
                        break
                    case 3: // Business
                        values.businessItems = [{ startDate: startDate || "", endDate: endDate || "", meetingName: "", organization: "" }]
                        break
                    case 4: // Personal
                        values.personalItems = [{
                            startDate: startDate || "",
                            endDate: endDate || "",
                            type: "",
                            details: "",
                            phone: "",
                            route: "",
                            relation: "",
                            visitName: "",
                            visitType: "",
                            visitAddress: "",
                            maritalStatus: "",
                            parity: "",
                            multiple: "",
                            dystocia: ""
                        }]
                        break
                    case 5: // Academic
                        values.academicItems = [{ 
                            startDate: startDate || "", 
                            endDate: endDate || "", 
                            meetingName: "", 
                            organizer: "", 
                            nature: "", 
                            hasReport: "", 
                            reportType: "",
                            reportTitle: "",
                            academicPaperCount: 0 
                        }]
                        break
                    case 6: // Other
                        values.otherItems = [{ description: "" }]
                        break
                }
            })
        }

        return values
    }, [selectedReasons, startDate, endDate, editReasonData])

    const {
        control,
        watch,
        reset,
    } = useForm<LeaveFormData>({
        defaultValues: defaultValues,
        // 编辑模式下不使用本地存储的默认值
        mode: editReasonData ? 'onChange' : 'onSubmit'
    })

    // 各种数组字段
    const researchArray = useFieldArray({ control, name: "researchItems" })
    const trainingArray = useFieldArray({ control, name: "trainingItems" })
    const businessArray = useFieldArray({ control, name: "businessItems" })
    const personalArray = useFieldArray({ control, name: "personalItems" })
    const academicArray = useFieldArray({ control, name: "academicItems" })
    const otherArray = useFieldArray({ control, name: "otherItems" })

    // 编辑模式下的删除标记状态
    const [deletedItems, setDeletedItems] = useState<{
        researchItems: string[],
        trainingItems: string[],
        businessItems: string[],
        personalItems: string[],
        academicItems: string[],
        otherItems: string[]
    }>({
        researchItems: [],
        trainingItems: [],
        businessItems: [],
        personalItems: [],
        academicItems: [],
        otherItems: []
    })

    // 日期选择器状态
    const [showDatePickers, setShowDatePickers] = useState<{ [key: string]: boolean }>({})

    const currentReason = selectedReasons[currentReasonIndex]
    
    // 使用useMemo避免无限循环
    const currentReasonOption = useMemo(() => {
        // 使用getIntDictOptions确保返回的value是数字类型
        const options = getIntDictOptions(DICT_TYPE.LEAVE_TYPE)
        // 将currentReason转换为数字进行比较，确保类型一致
        const currentReasonNum = Number(currentReason)
        const found = options.find(opt => opt.value === currentReasonNum)
        
        return found
    }, [getIntDictOptions, currentReason])

    // 使用请假提交 Hook
    const { isSubmitting, validateFormData, submitLeaveApplication } = useLeaveSubmission({
        selectedReasons,
        startDate,
        endDate,
        mainLeaveData,
        onSave,
        isEditMode: !!editReasonData,
        editData: editReasonData ? {
            registerId: mainLeaveData?.registerId,
            existingFiles: editReasonData
        } : undefined
    })

    // 生成存储键名
    const getStorageKey = useCallback(() => {
        return `leave_reason_detail_${startDate}_${endDate}`
    }, [startDate, endDate])

    // 清空所有可能的草稿键
    const clearAllDraftKeys = useCallback(async () => {
        try {
            // 清空新的存储key
            const newStorageKey = getStorageKey()
            await AsyncStorage.removeItem(newStorageKey)
            
            // 清空旧的存储key（基于请假类型的）
            const reasonTypes = selectedReasons.sort().join('_')
            const oldStorageKey = `leave_reason_detail_${reasonTypes}_${startDate}_${endDate}`
            await AsyncStorage.removeItem(oldStorageKey)
            
            setHasDraft(false)
            setIsFormDirty(false)
            console.log('所有草稿数据已清空')
        } catch (error) {
            console.error('清空草稿失败:', error)
        }
    }, [getStorageKey, selectedReasons, startDate, endDate])

    // 保存草稿到本地存储
    const saveDraftToStorage = useCallback(async () => {
        try {
            const currentFormData = watch()
            const storageKey = getStorageKey()
            
            // 检查表单是否有实际内容
            const hasContent = Object.values(currentFormData).some(items => 
                Array.isArray(items) && items.length > 0 && 
                items.some(item => Object.values(item).some(value => 
                    value !== null && value !== undefined && value !== ""
                ))
            )
            
            if (hasContent) {
                // 保存时包含当前选择的请假类型，用于恢复时的兼容性检查
                const draftData = {
                    formData: currentFormData,
                    selectedReasons: selectedReasons, // 保存当前选择的请假类型
                    timestamp: Date.now()
                }
                await AsyncStorage.setItem(storageKey, JSON.stringify(draftData))
                setHasDraft(true)
                return true
            }
            return false
        } catch (error) {
            console.error('保存草稿失败:', error)
            return false
        }
    }, [watch, getStorageKey, selectedReasons])

    // 检查是否有草稿
    const checkForDraft = useCallback(async () => {
        try {
            const storageKey = getStorageKey()
            const savedData = await AsyncStorage.getItem(storageKey)
            setHasDraft(!!savedData)
            return !!savedData
        } catch (error) {
            console.error('检查草稿失败:', error)
            return false
        }
    }, [getStorageKey])



    // 从AsyncStorage恢复数据
    const loadDataFromStorage = useCallback(async () => {
        try {
            const storageKey = getStorageKey()
            const savedData = await AsyncStorage.getItem(storageKey)

            if (savedData) {
                const parsedData = JSON.parse(savedData)
                console.log('从本地存储恢复数据:', parsedData)

                // 检查是否是新格式的数据
                let formData
                if (parsedData.formData) {
                    formData = parsedData.formData
                } else {
                    formData = parsedData
                }

                // 只恢复当前选择的请假类型对应的数据
                const mergedData: any = {
                    researchItems: [],
                    trainingItems: [],
                    businessItems: [],
                    personalItems: [],
                    academicItems: [],
                    otherItems: [],
                }

                // 根据当前选择的请假类型，恢复对应的数据
                selectedReasons.forEach(reason => {
                    const reasonNum = Number(reason)
                    switch (reasonNum) {
                        case 1: // Research
                            if (formData.researchItems && formData.researchItems.length > 0) {
                                mergedData.researchItems = formData.researchItems
                            } else {
                                // 如果没有草稿数据，创建默认项
                                mergedData.researchItems = [{ 
                                    startDate: startDate || "", 
                                    endDate: endDate || "", 
                                    theme: "", 
                                    purpose: "", 
                                    organization: "" 
                                }]
                            }
                            break
                        case 2: // Training
                            if (formData.trainingItems && formData.trainingItems.length > 0) {
                                mergedData.trainingItems = formData.trainingItems
                            } else {
                                mergedData.trainingItems = [{ 
                                    startDate: startDate || "", 
                                    endDate: endDate || "", 
                                    theme: "", 
                                    organization: "" 
                                }]
                            }
                            break
                        case 3: // Business
                            if (formData.businessItems && formData.businessItems.length > 0) {
                                mergedData.businessItems = formData.businessItems
                            } else {
                                mergedData.businessItems = [{ 
                                    startDate: startDate || "", 
                                    endDate: endDate || "", 
                                    meetingName: "", 
                                    organization: "" 
                                }]
                            }
                            break
                        case 4: // Personal
                            if (formData.personalItems && formData.personalItems.length > 0) {
                                mergedData.personalItems = formData.personalItems
                            } else {
                                mergedData.personalItems = [{
                                    startDate: startDate || "",
                                    endDate: endDate || "",
                                    type: "",
                                    details: "",
                                    phone: "",
                                    route: "",
                                    relation: "",
                                    visitName: "",
                                    visitType: "",
                                    visitAddress: "",
                                    maritalStatus: "",
                                    parity: "",
                                    multiple: "",
                                    dystocia: ""
                                }]
                            }
                            break
                        case 5: // Academic
                            if (formData.academicItems && formData.academicItems.length > 0) {
                                mergedData.academicItems = formData.academicItems
                            } else {
                                mergedData.academicItems = [{ 
                                    startDate: startDate || "", 
                                    endDate: endDate || "", 
                                    meetingName: "", 
                                    organizer: "", 
                                    nature: "", 
                                    hasReport: "", 
                                    reportType: "",
                                    reportTitle: "",
                                    academicPaperCount: 0 
                                }]
                            }
                            break
                        case 6: // Other
                            if (formData.otherItems && formData.otherItems.length > 0) {
                                mergedData.otherItems = formData.otherItems
                            } else {
                                mergedData.otherItems = [{ description: "" }]
                            }
                            break
                    }
                })

                // 先清空所有数组，避免重复
                researchArray.replace([])
                trainingArray.replace([])
                businessArray.replace([])
                personalArray.replace([])
                academicArray.replace([])
                otherArray.replace([])

                // 重置表单数据
                reset(mergedData)

                if (mergedData.researchItems && mergedData.researchItems.length > 0) {
                    researchArray.replace(mergedData.researchItems)
                }
                if (mergedData.trainingItems && mergedData.trainingItems.length > 0) {
                    trainingArray.replace(mergedData.trainingItems)
                }
                if (mergedData.businessItems && mergedData.businessItems.length > 0) {
                    businessArray.replace(mergedData.businessItems)
                }
                if (mergedData.personalItems && mergedData.personalItems.length > 0) {
                    personalArray.replace(mergedData.personalItems)
                }
                if (mergedData.academicItems && mergedData.academicItems.length > 0) {
                    academicArray.replace(mergedData.academicItems)
                }
                if (mergedData.otherItems && mergedData.otherItems.length > 0) {
                    otherArray.replace(mergedData.otherItems)
                }

                setIsDataLoaded(true)
                return true
            }
        } catch (error) {
            console.error('从本地存储恢复数据失败:', error)
        }
        return false
    }, [getStorageKey, reset, researchArray, trainingArray, businessArray, personalArray, academicArray, otherArray, selectedReasons, startDate, endDate])

    // 标记项目为删除状态（编辑模式下）
    const markItemForDeletion = useCallback((type: keyof typeof deletedItems, itemId: string) => {
        if (editReasonData) {
            setDeletedItems(prev => ({
                ...prev,
                [type]: [...prev[type], itemId]
            }))
        }
    }, [editReasonData])

    // 初始化完成标记
    const markInitializationComplete = useCallback(() => {
        setIsDataLoaded(true)
    }, [])

    useEffect(() => {
        const loadSavedData = async () => {
            if (editReasonData) {
                markInitializationComplete()
                return
            }
            
            if (!isDataLoaded) {
                // 先检查是否有草稿
                await checkForDraft()
                
                const hasSavedData = await loadDataFromStorage()
                if (!hasSavedData) {
                    // 没有保存数据时，使用默认值（已经在表单初始化时设置）
                    markInitializationComplete()
                }
                // 如果有保存数据，loadDataFromStorage 中已经调用了 setIsDataLoaded(true)
            }
        }

        loadSavedData()
    }, [loadDataFromStorage, markInitializationComplete, isDataLoaded, editReasonData, checkForDraft])

    // 监听表单变化
    useEffect(() => {
        if (!isDataLoaded || editReasonData) return
        
        const subscription = watch(() => {
            setIsFormDirty(true)
        })
        
        return () => subscription.unsubscribe()
    }, [watch, isDataLoaded, editReasonData])

    // 页面获得焦点时的处理
    useFocusEffect(
        useCallback(() => {
            // 页面获得焦点时检查草稿
            if (!editReasonData) {
                checkForDraft()
            }

            // 设置导航头部的返回按钮处理
            const unsubscribe = navigation.addListener('beforeRemove', (e) => {
                if (!isFormDirty || editReasonData || isSubmitted || isShowingAlert) {
                    return
                }

                // 阻止默认行为
                e.preventDefault()
                
                // 设置正在显示弹窗标志
                setIsShowingAlert(true)

                Alert.alert(
                    '保存草稿',
                    '检测到您填写了表单内容，是否要保存为草稿？',
                    [
                        { 
                            text: '不保存', 
                            style: 'destructive', 
                            onPress: async () => {
                                setIsShowingAlert(false)
                                // 重置表单dirty状态，防止再次触发
                                setIsFormDirty(false)
                                // 用户选择不保存时，清空已有的草稿
                                await clearAllDraftKeys()
                                navigation.dispatch(e.data.action)
                            }
                        },
                        { 
                            text: '保存草稿', 
                            onPress: async () => {
                                await saveDraftToStorage()
                                // 重置表单dirty状态，防止再次触发
                                setIsFormDirty(false)
                                setIsShowingAlert(false)
                                // 执行原本的导航动作
                                navigation.dispatch(e.data.action)
                            }
                        },
                        { 
                            text: '取消', 
                            style: 'cancel',
                            onPress: () => setIsShowingAlert(false)
                        }
                    ]
                )
            })

            // 处理Android返回键
            const onBackPress = () => {
                if (isFormDirty && !editReasonData && !isSubmitted && !isShowingAlert) {
                    // 设置正在显示弹窗标志
                    setIsShowingAlert(true)
                    
                    Alert.alert(
                        '保存草稿',
                        '检测到您填写了表单内容，是否要保存为草稿？',
                        [
                            { 
                                text: '不保存', 
                                style: 'destructive', 
                                onPress: async () => {
                                    setIsShowingAlert(false)
                                    // 重置表单dirty状态，防止再次触发
                                    setIsFormDirty(false)
                                    // 用户选择不保存时，清空已有的草稿
                                    await clearAllDraftKeys()
                                    navigation.goBack()
                                }
                            },
                            { 
                                text: '保存草稿', 
                                onPress: async () => {
                                    await saveDraftToStorage()
                                    // 重置表单dirty状态，防止再次触发
                                    setIsFormDirty(false)
                                    setIsShowingAlert(false)
                                    // 直接返回
                                    navigation.goBack()
                                }
                            },
                            { 
                                text: '取消', 
                                style: 'cancel',
                                onPress: () => setIsShowingAlert(false)
                            }
                        ]
                    )
                    return true
                }
                return false
            }

            const backHandler = BackHandler.addEventListener('hardwareBackPress', onBackPress)
            
            return () => {
                unsubscribe()
                backHandler.remove()
            }
        }, [isFormDirty, editReasonData, navigation, checkForDraft, saveDraftToStorage, isSubmitted, isShowingAlert, clearAllDraftKeys])
    )

    const handleSave = async () => {
        try {
        const currentFormData = watch()

            // 验证必填字段
        const formData = {
            researchItems: currentFormData.researchItems || [],
            trainingItems: currentFormData.trainingItems || [],
            businessItems: currentFormData.businessItems || [],
            personalItems: currentFormData.personalItems || [],
            academicItems: currentFormData.academicItems || [],
            otherItems: currentFormData.otherItems || [],
        }

            // 使用 Hook 验证数据
            if (!validateFormData(formData)) {
                return
            }

            console.log('准备提交请假申请数据:', formData)

            // 显示确认提交对话框
            Alert.alert(
                editReasonData ? '确认更新' : '确认提交',
                editReasonData ? '确定要更新请假申请吗？' : '确定要提交请假申请吗？',
                [
                    { text: '取消', style: 'cancel' },
                    {
                        text: editReasonData ? '确定更新' : '确定提交',
                        style: 'destructive',
                        onPress: async () => {
                            const submissionData = editReasonData ? {
                                ...formData,
                                deletedItems: editReasonData ? deletedItems : undefined
                            } : formData
                            
                            const success = await submitLeaveApplication(submissionData)

                            if (success) {
                                // 标记已提交，防止返回时再次询问保存草稿
                                setIsSubmitted(true)
                                
                                // 清空草稿数据
                                await clearAllDraftKeys()
                                
                                // 显示提交成功提示
                                Alert.alert(
                                    editReasonData ? '更新成功' : '提交成功',
                                    editReasonData ? '请假申请已成功更新。' : '请假申请已成功提交，请等待审批。\n\n您可以在"我的申请"中查看申请状态。',
                                    [
                                        {
                                            text: '确定',
                                            onPress: () => {
                                                // 清空所有表单数据
                                                reset({
                                                    researchItems: [],
                                                    trainingItems: [],
                                                    businessItems: [],
                                                    personalItems: [],
                                                    academicItems: [],
                                                    otherItems: [],
                                                })

                                                // 清空所有数组字段
                                                researchArray.replace([])
                                                trainingArray.replace([])
                                                businessArray.replace([])
                                                personalArray.replace([])
                                                academicArray.replace([])
                                                otherArray.replace([])

                                                // 重置数据加载状态
                                                setIsDataLoaded(false)
                                                setIsFormDirty(false)

                                                // 跳转到请假列表页面
                                                navigation.dispatch(
                                                    CommonActions.reset({
                                                        index: 0,
                                                        routes: [{ name: 'LeaveList' }],
                                                    })
                                                )
                                            }
                                        }
                                    ]
                                )
                            }
                        }
                    }
                ]
            )

        } catch (error) {
            console.error('处理提交时发生错误:', error)
            Alert.alert('错误', '提交过程中发生错误，请重试')
        }
    }

    const renderReasonTabs = useCallback(() => {
        return (
            <View style={leaveStyles.reasonTabs}>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    {selectedReasons.map((reason, index) => {
                        const reasonNum = Number(reason)
                        const option = getIntDictOptions(DICT_TYPE.LEAVE_TYPE).find(opt => opt.value === reasonNum)
                        return (
                            <TouchableOpacity
                                key={reason}
                                style={[
                                    leaveStyles.reasonTab,
                                    currentReasonIndex === index && leaveStyles.activeReasonTab
                                ]}
                                onPress={() => setCurrentReasonIndex(index)}
                            >
                                <Text style={[
                                    leaveStyles.reasonTabText,
                                    currentReasonIndex === index && leaveStyles.activeReasonTabText
                                ]}>
                                    {option?.label || `类型${reason}`}
                                </Text>
                            </TouchableOpacity>
                        )
                    })}
                </ScrollView>
            </View>
        )
    }, [selectedReasons, currentReasonIndex, getIntDictOptions])

    const renderCurrentReasonForm = () => {
        // 将currentReason转换为数字进行比较
        const currentReasonNum = Number(currentReason)
        
        switch (currentReasonNum) {
            case 1: // Research
                return (
                    <ResearchForm
                        control={control}
                        watch={watch}
                        startDate={startDate}
                        endDate={endDate}
                        showDatePickers={showDatePickers}
                        setShowDatePickers={setShowDatePickers}
                        isEditMode={!!editReasonData}
                        onMarkForDeletion={(itemId) => markItemForDeletion('researchItems', itemId)}
                        getValues={() => control._formValues}
                    />
                )
            case 2: // Training
                return (
                    <TrainingForm
                        control={control}
                        watch={watch}
                        startDate={startDate}
                        endDate={endDate}
                        showDatePickers={showDatePickers}
                        setShowDatePickers={setShowDatePickers}
                        isEditMode={!!editReasonData}
                        onMarkForDeletion={(itemId) => markItemForDeletion('trainingItems', itemId)}
                        getValues={() => control._formValues}
                    />
                )
            case 3: // Business
                return (
                    <BusinessForm
                        control={control}
                        watch={watch}
                        startDate={startDate}
                        endDate={endDate}
                        showDatePickers={showDatePickers}
                        setShowDatePickers={setShowDatePickers}
                        isEditMode={!!editReasonData}
                        onMarkForDeletion={(itemId) => markItemForDeletion('businessItems', itemId)}
                        getValues={() => control._formValues}
                    />
                )
            case 4: // Personal
                return (
                    <PersonalForm
                        control={control}
                        watch={watch}
                        startDate={startDate}
                        endDate={endDate}
                        showDatePickers={showDatePickers}
                        setShowDatePickers={setShowDatePickers}
                        isEditMode={!!editReasonData}
                        onMarkForDeletion={(itemId) => markItemForDeletion('personalItems', itemId)}
                        getValues={() => control._formValues}
                    />
                )
            case 5: // Academic
                return (
                    <AcademicForm
                        control={control}
                        watch={watch}
                        startDate={startDate}
                        endDate={endDate}
                        showDatePickers={showDatePickers}
                        setShowDatePickers={setShowDatePickers}
                        isEditMode={!!editReasonData}
                        onMarkForDeletion={(itemId) => markItemForDeletion('academicItems', itemId)}
                        getValues={() => control._formValues}
                    />
                )
            case 6: // Other
                return (
                    <OtherForm
                        control={control}
                        watch={watch}
                        _isEditMode={!!editReasonData}
                        _onMarkForDeletion={(itemId) => markItemForDeletion('otherItems', itemId)}
                        _getValues={() => control._formValues}
                    />
                )
            default:
                return (
        <View style={leaveStyles.reasonFormContainer}>
            <Text style={leaveStyles.reasonFormTitle}>
                {currentReasonOption?.label} 详细信息
            </Text>
            <Text style={leaveStyles.reasonFormDescription}>
                请填写 {currentReasonOption?.label} 的详细信息
            </Text>
        </View>
    )
        }
    }

    return (
        <SafeAreaView style={leaveStyles.container}>
            {renderReasonTabs()}

            <ScrollView style={leaveStyles.scrollView}>
                {renderCurrentReasonForm()}
            </ScrollView>

            {/* 提交申请按钮 */}
            <View style={leaveStyles.buttonContainer}>
                <TouchableOpacity
                    style={[
                        leaveStyles.saveButton,
                        isSubmitting && leaveStyles.disabledOpacity
                    ]}
                    onPress={handleSave}
                    disabled={isSubmitting}
                >
                    <Text style={leaveStyles.saveButtonText}>
                        {isSubmitting ? '提交中...' : (editReasonData ? '更新申请' : '提交申请')}
                    </Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    )
}
